<template>
  <div>

    <el-card>
      <el-row :gutter="30">
        <el-col :span="5">
          <el-input placeholder="类型名称" v-model="searchName" ></el-input>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="success" icon="el-icon-search" @click="handleSearchType" plain>搜索</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="warning" icon="el-icon-refresh-left" @click="handleResetType" plain>重置</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="primary" icon="el-icon-plus" @click="dialogVisible = true" plain>添加</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="danger" icon="el-icon-delete" @click="batchDeleteType" plain>删除</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <el-row>
        <el-table
            stripe
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
        >
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="name"
              label="类型名称"
              width="120">
          </el-table-column>
          <el-table-column
              prop="remarks"
              label="备注"
              width="580">
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="145"
              header-align="center">
            <template slot-scope="scope">
              <div style="display: flex; justify-content: center;">
              <el-button @click="handleClick(scope.row)" type="primary" plain icon="el-icon-edit" circle size="small"></el-button>
              <el-button type="danger" plain icon="el-icon-delete" circle size="small" @click="deleteType(scope.row)"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="pageData.currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size=pageData.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total">
        </el-pagination>
      </el-row>
    </el-card>

    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose">
      <el-form :model="typeForm" :rules="rules" ref="readerForm">
        <el-form-item label="类型名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="typeForm.name" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="备注信息" :label-width="formLabelWidth">
          <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="typeForm.remarks">
          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelDialog">取 消</el-button>
    <el-button type="primary" plain @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "TypeViews",
  created() {
    this.getTypeList()
  },
  data() {
    return {
      typeForm: {
        name: '',
        remarks: '',
        id: ''
      },
      dialogVisible: false,
      formLabelWidth: '90px',
      searchName: '',
      currentSearchName: '',
      tableData: [],
      pageData:{
        currentPage:1,
        pageSize:5,
        total:0
      },
      rules: {
        name: [
          { required: true, message: '请输入类型名称', trigger: 'blur' },
        ]
      },
      dialogTitle: '添加类型'
    }
  },
  methods: {
    currentChange(val){
      this.pageData.currentPage=val
      this.getTypeList(this.currentSearchName);
    },
    sizeChange(val){
      this.pageData.pageSize=val
      this.getTypeList(this.currentSearchName);
    },
    async getTypeList(name = '') {
      const params = {...this.pageData, name: name};
      const {data: res} = await this.$axios.get("typeInfo/getTypeInfo",{params})
      console.log(res.data.records)
      this.tableData=res.data.records
      this.pageData.total=res.data.total
    },
    deleteType(row){
      this.$confirm('此操作将永久删除该类型, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data:res}=await this.$axios.get("typeInfo/deleteById",{params:{id:row.id}})
        if (res.success){
          this.$message.success('删除成功')
          await this.getTypeList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    batchDeleteType() {
      const selectedRows = this.$refs.multipleTable.selection;
      if (selectedRows.length === 0) {
        this.$message.warning('请选择要删除的类型');
        return;
      }
      this.$confirm('此操作将永久删除选中的类型, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ids = selectedRows.map(row => row.id);
        const { data: res } = await this.$axios.post("typeInfo/batchDeleteType", ids);
        if (res.success) {
          this.$message.success('删除成功');
          await this.getTypeList();
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSearchType() {
      this.pageData.currentPage = 1; // 搜索时重置页码
      this.currentSearchName = this.searchName;// 设置当前搜索关键字
      this.getTypeList(this.searchName);
    },
    handleResetType(){
      this.searchName = '';
      this.currentSearchName = ''; // 重置当前搜索关键字
      this.pageData.currentPage = 1;
      this.getTypeList();
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.resetForm();
            this.$refs.readerForm.resetFields(); // 清除表单验证状态
            done();
          })
          .catch(_ => {});
    },
    handleClick(row) {
      this.dialogTitle = '修改类型';
      this.dialogVisible = true;
      this.typeForm = { ...row }; // 填充表单数据
    },
    async submitForm() {
      try {
        await this.$refs.readerForm.validate(async (valid) => {
          if (valid) {
            if (this.typeForm.id) {
              // 修改操作
              const { data: res } = await this.$axios.put('/typeInfo/updateType', this.typeForm);
              if (res.success) {
                this.$message.success('修改成功');
                this.dialogVisible = false;
                this.getTypeList(); // 刷新列表
                this.resetForm(); // 重置表单
              } else {
                this.$message.error(res.message || '修改失败');
              }
            } else {
              // 添加操作
              const { data: res } = await this.$axios.post('/typeInfo/addType', this.typeForm);
              if (res.success) {
                this.$message.success('添加成功');
                this.dialogVisible = false;
                this.getTypeList(); // 刷新列表
                this.resetForm(); // 重置表单
              } else {
                this.$message.error(res.message || '添加失败');
              }
            }
          } else {
            this.$message.error('表单验证未通过，请检查输入');
            return false;
          }
        });
      } catch (error) {
        console.error(error);
        this.$message.error('请求失败，请稍后再试');
      }
    },
    cancelDialog() {
      this.resetForm(); // 重置表单数据
      this.$refs.readerForm.clearValidate(); // 清除表单验证状态
      this.dialogVisible = false; // 关闭对话框
    },
    resetForm() {
      this.typeForm = {
        name: '',
        remarks: '',
        id: ''
      };
    },
  }
}
</script>

<style scoped>
.el-pagination{
  margin-top: 10px;
}
</style>